<template>
  <div class="page-header">
    <h2 class="page-title">
      <el-icon class="title-icon"><Files /></el-icon>
      公文发送
    </h2>
    <el-button type="primary" @click="saveAsDraft">
      <el-icon><Document /></el-icon>
      保存草稿
    </el-button>
  </div>

  <!-- 申请表单 -->
  <el-card class="form-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <span>公文信息</span>
        <el-tag type="info">请填写完整的公文信息</el-tag>
      </div>
    </template>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="document-form"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发文人" prop="sender">
              <el-input v-model="formData.sender" placeholder="请输入发文人姓名" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-input v-model="formData.department" placeholder="请输入部门名称" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="formData.position" placeholder="请输入职位" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 公文信息 -->
      <div class="form-section">
        <h3 class="section-title">公文信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公文类型" prop="documentType">
              <el-select
                v-model="formData.documentType"
                placeholder="请选择公文类型"
                style="width: 100%"
              >
                <el-option label="通知" value="notice" />
                <el-option label="报告" value="report" />
                <el-option label="请示" value="request" />
                <el-option label="批复" value="reply" />
                <el-option label="决定" value="decision" />
                <el-option label="意见" value="opinion" />
                <el-option label="函" value="letter" />
                <el-option label="纪要" value="summary" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急程度" prop="urgency">
              <el-select
                v-model="formData.urgency"
                placeholder="请选择紧急程度"
                style="width: 100%"
              >
                <el-option label="普通" value="normal" />
                <el-option label="紧急" value="urgent" />
                <el-option label="特急" value="very_urgent" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="密级" prop="securityLevel">
              <el-select
                v-model="formData.securityLevel"
                placeholder="请选择密级"
                style="width: 100%"
              >
                <el-option label="公开" value="public" />
                <el-option label="内部" value="internal" />
                <el-option label="秘密" value="secret" />
                <el-option label="机密" value="confidential" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发送日期" prop="sendDate">
              <el-date-picker
                v-model="formData.sendDate"
                type="date"
                placeholder="选择发送日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="公文标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入公文标题" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 收件人信息 -->
      <div class="form-section">
        <h3 class="section-title">收件人信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="主送单位" prop="mainRecipient">
              <el-select
                v-model="formData.mainRecipient"
                placeholder="请选择主送单位"
                style="width: 100%"
                multiple
                filterable
              >
                <el-option label="技术部" value="tech" />
                <el-option label="人事部" value="hr" />
                <el-option label="财务部" value="finance" />
                <el-option label="市场部" value="marketing" />
                <el-option label="运营部" value="operation" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抄送单位" prop="ccRecipient">
              <el-select
                v-model="formData.ccRecipient"
                placeholder="请选择抄送单位"
                style="width: 100%"
                multiple
                filterable
              >
                <el-option label="技术部" value="tech" />
                <el-option label="人事部" value="hr" />
                <el-option label="财务部" value="finance" />
                <el-option label="市场部" value="marketing" />
                <el-option label="运营部" value="operation" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="收件人" prop="recipients">
              <el-select
                v-model="formData.recipients"
                placeholder="请选择收件人"
                style="width: 100%"
                multiple
                filterable
                remote
                :remote-method="searchRecipients"
                :loading="recipientLoading"
              >
                <el-option
                  v-for="item in recipientOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 公文内容 -->
      <div class="form-section">
        <h3 class="section-title">公文内容</h3>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="正文内容" prop="content">
              <el-input
                v-model="formData.content"
                type="textarea"
                :rows="8"
                placeholder="请输入公文正文内容"
                maxlength="2000"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注说明" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注说明（可选）"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 附件上传 -->
      <div class="form-section">
        <h3 class="section-title">附件上传</h3>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="相关附件">
              <el-upload
                ref="uploadRef"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :file-list="fileList"
                :on-preview="handleFilePreview"
                :on-remove="handleFileRemove"
                :before-remove="beforeFileRemove"
                :on-success="handleFileSuccess"
                :on-error="handleFileError"
                multiple
                :limit="10"
                list-type="text"
                accept=".doc,.docx,.pdf,.txt,.xls,.xlsx"
              >
                <el-button type="primary">
                  <el-icon><Upload /></el-icon>
                  点击上传
                </el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持doc/docx/pdf/txt/xls/xlsx格式，单个文件不超过20MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 审批流程 -->
      <div class="form-section">
        <h3 class="section-title">审批流程</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门审核" prop="departmentReviewer">
              <el-select
                v-model="formData.departmentReviewer"
                placeholder="请选择部门审核人"
                style="width: 100%"
              >
                <el-option label="张经理" value="zhang" />
                <el-option label="李总监" value="li" />
                <el-option label="王总" value="wang" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="办公室审核" prop="officeReviewer">
              <el-select
                v-model="formData.officeReviewer"
                placeholder="请选择办公室审核人"
                style="width: 100%"
              >
                <el-option label="陈主任" value="chen" />
                <el-option label="刘主任" value="liu" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="info" @click="saveAsDraft">保存草稿</el-button>
        <el-button type="primary" @click="submitForm">发送公文</el-button>
      </div>
    </el-form>
  </el-card>

  <!-- 公文统计 -->
  <el-card class="stats-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <span>公文统计</span>
      </div>
    </template>

    <el-row :gutter="20">
      <el-col :span="6">
        <div class="stat-item">
          <div class="stat-icon total-icon">
            <el-icon><Files /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ documentStats.total }}</div>
            <div class="stat-label">总公文数</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-item">
          <div class="stat-icon sent-icon">
            <el-icon><Message /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ documentStats.sent }}</div>
            <div class="stat-label">已发送</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-item">
          <div class="stat-icon pending-icon">
            <el-icon><Timer /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ documentStats.pending }}</div>
            <div class="stat-label">待审核</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-item">
          <div class="stat-icon urgent-icon">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ documentStats.urgent }}</div>
            <div class="stat-label">紧急公文</div>
          </div>
        </div>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { Files, Document, Upload, Message, Timer, Warning } from '@element-plus/icons-vue'

// 表单引用
const formRef = ref<FormInstance>()
const uploadRef = ref()

// 表单数据
const formData = reactive({
  sender: '张三',
  department: '技术部',
  position: '前端工程师',
  phone: '13800138000',
  documentType: '',
  urgency: 'normal',
  securityLevel: 'public',
  sendDate: '',
  title: '',
  mainRecipient: [],
  ccRecipient: [],
  recipients: [],
  content: '',
  remark: '',
  departmentReviewer: '',
  officeReviewer: '',
})

// 表单验证规则
const formRules: FormRules = {
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  documentType: [{ required: true, message: '请选择公文类型', trigger: 'change' }],
  urgency: [{ required: true, message: '请选择紧急程度', trigger: 'change' }],
  securityLevel: [{ required: true, message: '请选择密级', trigger: 'change' }],
  sendDate: [{ required: true, message: '请选择发送日期', trigger: 'change' }],
  title: [
    { required: true, message: '请输入公文标题', trigger: 'blur' },
    { min: 5, message: '公文标题至少5个字符', trigger: 'blur' },
  ],
  mainRecipient: [{ required: true, message: '请选择主送单位', trigger: 'change' }],
  content: [
    { required: true, message: '请输入公文内容', trigger: 'blur' },
    { min: 20, message: '公文内容至少20个字符', trigger: 'blur' },
  ],
  departmentReviewer: [{ required: true, message: '请选择部门审核人', trigger: 'change' }],
  officeReviewer: [{ required: true, message: '请选择办公室审核人', trigger: 'change' }],
}

// 文件上传相关
const fileList = ref<UploadUserFile[]>([])
const uploadUrl = '/api/upload'
const uploadHeaders = {
  Authorization: 'Bearer token',
}

// 收件人搜索相关
const recipientLoading = ref(false)
const recipientOptions = ref([
  { label: '张三', value: 'zhangsan' },
  { label: '李四', value: 'lisi' },
  { label: '王五', value: 'wangwu' },
  { label: '赵六', value: 'zhaoliu' },
])

// 公文统计
const documentStats = reactive({
  total: 156,
  sent: 142,
  pending: 8,
  urgent: 6,
})

// 搜索收件人
const searchRecipients = (query: string) => {
  if (query !== '') {
    recipientLoading.value = true
    // 模拟搜索
    setTimeout(() => {
      recipientOptions.value = [
        { label: '张三', value: 'zhangsan' },
        { label: '李四', value: 'lisi' },
        { label: '王五', value: 'wangwu' },
        { label: '赵六', value: 'zhaoliu' },
      ].filter((item) => item.label.includes(query))
      recipientLoading.value = false
    }, 500)
  } else {
    recipientOptions.value = []
  }
}

// 文件上传处理
const handleFilePreview = (file: UploadUserFile) => {
  console.log(file)
}

const handleFileRemove = (file: UploadUserFile, fileList: UploadUserFile[]) => {
  console.log(file, fileList)
}

const beforeFileRemove = (file: UploadUserFile) => {
  return ElMessageBox.confirm(`确定移除 ${file.name}？`)
}

const handleFileSuccess = () => {
  ElMessage.success('文件上传成功')
}

const handleFileError = () => {
  ElMessage.error('文件上传失败')
}

// 表单操作
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  fileList.value = []
}

const saveAsDraft = () => {
  ElMessage.success('草稿保存成功')
}

const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 验证收件人
    if (formData.mainRecipient.length === 0) {
      ElMessage.error('请选择主送单位')
      return
    }

    if (formData.recipients.length === 0) {
      ElMessage.error('请选择收件人')
      return
    }

    // 验证公文内容
    if (formData.content.length < 20) {
      ElMessage.error('公文内容至少20个字符')
      return
    }

    // 模拟提交
    ElMessage.success('公文发送成功')
    resetForm()
  } catch (error) {
    ElMessage.error('请检查表单信息')
  }
}

// 初始化
onMounted(() => {
  // 可以在这里加载用户信息和公文统计
})
</script>

<style scoped lang="less">
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .page-title {
    display: flex;
    align-items: center;
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;

    .title-icon {
      margin-right: 8px;
      color: #409eff;
    }
  }
}

.form-card {
  margin-bottom: 20px;
  border-radius: 8px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
  }

  .document-form {
    .form-section {
      margin-bottom: 30px;
      padding-bottom: 20px;
      border-bottom: 1px solid #ebeef5;

      &:last-child {
        border-bottom: none;
      }

      .section-title {
        margin: 0 0 20px 0;
        color: #303133;
        font-size: 18px;
        font-weight: 600;
        position: relative;
        padding-left: 12px;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 4px;
          height: 18px;
          background-color: #409eff;
          border-radius: 2px;
        }
      }
    }

    .form-actions {
      display: flex;
      justify-content: center;
      gap: 16px;
      margin-top: 30px;
      padding-top: 20px;
      border-top: 1px solid #ebeef5;
    }
  }
}

.stats-card {
  border-radius: 8px;

  .card-header {
    font-weight: 600;
  }

  .stat-item {
    display: flex;
    align-items: center;
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      font-size: 24px;
      color: white;

      &.total-icon {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }

      &.sent-icon {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }

      &.pending-icon {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }

      &.urgent-icon {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      }
    }

    .stat-content {
      .stat-value {
        font-size: 24px;
        font-weight: 700;
        color: #303133;
        margin-bottom: 4px;
      }

      .stat-label {
        font-size: 14px;
        color: #909399;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .document-container {
    padding: 10px;

    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .page-title {
        font-size: 20px;
      }
    }

    .form-card {
      .document-form {
        .form-section {
          .section-title {
            font-size: 16px;
          }
        }

        .form-actions {
          flex-direction: column;
          align-items: center;
        }
      }
    }

    .stats-card {
      .stat-item {
        margin-bottom: 16px;
      }
    }
  }
}
</style>
